package com.roubsite.admin.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import com.roubsite.admin.bean.RsUsers;
import com.roubsite.admin.dao.user.IUserDao;
import com.roubsite.admin.dao.user.UserDao;
import com.roubsite.admin.utils.UserUtils;
import com.roubsite.database.annotation.Dao;
import com.roubsite.database.annotation.Trans;
import com.roubsite.database.bean.Record;
import com.roubsite.database.dao.DataSet;
import com.roubsite.security.annotation.RSSecRetType;
import com.roubsite.security.annotation.RSSecurity;
import com.roubsite.security.utils.RSPasswordUtil;
import com.roubsite.utils.JsonUtils;
import com.roubsite.utils.StringUtils;
import com.roubsite.utils.UuidUtils;
import com.roubsite.web.action.RSAction;

@SuppressWarnings("rawtypes")
public class UserAction extends AdminAction {
    @Dao(impl = UserDao.class, dataSource = "dataSource")
    IUserDao userDao;

    @RSSecurity
    @Override
    public void execute() throws Exception {
        this.assign("organId", this.I("organId"));
        this.display("/security/user/listUser.html");
    }

    @RSSecurity(retType = RSSecRetType.retJson)
    public void doQuery() throws IOException {
        Record record = new Record();
        Map paramSet = (Map) this.getParamSet(false);
        record.fromBeanMap((Map) paramSet.get("__data__"));
        DataSet ret = userDao.queryd(record, (int) paramSet.get("__offset__"), (int) paramSet.get("__limit__"));
        this.print(JsonUtils.convertToString(ret));
    }

    @RSSecurity(retType = RSSecRetType.retJson)
    @Trans
    public void doDel() throws Exception {
        String jsonString = (String) this.getParamSet(true);
        List ids = JsonUtils.readToObject(jsonString, ArrayList.class);
        int r = userDao.del(ids);
        Map ret = new HashMap();
        ret.put("status", r);
        this.print(JsonUtils.convertToString(ret));
    }

    @RSSecurity
    @Trans
    public void doEdit() throws ServletException, IOException {
        String editState = this.I("editState");
        String method = this.I("method");
        String organ_id = this.$_G("organId");
        if (StringUtils.isEmpty(editState)) {
            // 正常打开页面
            if ("UPDATE".equals(method)) {
                String id = this.I("id");
                DataSet ret = userDao.getUserInfoById(id);
                this.assign("retInfo", JsonUtils.convertToString(ret));
            }
            this.assign("organId", this.I("organId"));
            this.assign("method", method);
            this.display("/security/user/editUser.html");
            return;
        }
        // 有数据提交
        String paramSet = (String) this.getParamSet(true);
        Record r = new Record();
        r.setState(Integer.parseInt(editState));
        r.fromJson(paramSet);
        if (!StringUtils.isNotEmptyObject(r.get("USER_ID"))) {
            String uid = UuidUtils.getUuid();
            // 新增加用户
            r.set("CREATE_TIME", Long.toString(System.currentTimeMillis()));
            r.set("PWD_TIME", Long.toString(System.currentTimeMillis()));
            r.set("USER_ID", uid);
            r.set("USER_PASSWORD", new RSPasswordUtil().encode((String) r.get("USER_PASSWORD")));
            userDao.editUserOrgan(uid, organ_id);
        } else {
            // 修改用户
            String pass = (String) r.get("USER_PASSWORD");
            DataSet ds = userDao.getUserInfoById((String) r.get("USER_ID"));
            if (ds.getCount() > 0) {
                RsUsers rsUsers = (RsUsers) ds.getRows().get(0);
                if (null != pass && pass.equals(rsUsers.getUserPassword())) {
                    r.set("USER_PASSWORD", pass);
                } else {
                    r.set("USER_PASSWORD", new RSPasswordUtil().encode(pass));
                    r.set("PWD_UP_TIME", Long.toString(System.currentTimeMillis()));
                }
            } else {
                r.set("PWD_UP_TIME", Long.toString(System.currentTimeMillis()));
                r.set("USER_PASSWORD", new RSPasswordUtil().encode(pass));
            }
        }
        int status = userDao.saveData(r, RsUsers.class);
        Map ret = new HashMap();
        ret.put("status", status);
        this.print(JsonUtils.convertToString(ret));

    }

    /**
     * 添加用户界面
     */

    @RSSecurity
    public void doAddUser() throws ServletException, IOException {
        String organId = this.$_G("organId");
        this.assign("organId", organId);
        this.display("user/addUser.html");
    }

    @RSSecurity
    @Trans
    public void doAddUserSubmit() throws IOException {
        Map retMap = new HashMap();
        String organ_id = this.$_G("organId");
        UserUtils uu = new UserUtils(userDao);
        String paramSet = (String) this.getParamSet(true);
        Record r = new Record();
        r.fromJson(paramSet);
        RsUsers user = (RsUsers) r.toBean(RsUsers.class);
        retMap.put("status", uu.register(UuidUtils.getUuid(), user.getUserName(), new RSPasswordUtil().encode(user.getUserPassword()),
                "addUser", organ_id));
        this.print(JsonUtils.convertToString(retMap));
    }

    /**
     * 修改用户界面
     */
    @RSSecurity
    public void doEditUser() throws IOException, ServletException {
        String id = this.$_G("id");
        DataSet ret = userDao.getUserInfoById(id);
        this.assign("retInfo", JsonUtils.convertToString(ret));
        this.display("user/editUser.html");
    }

    @RSSecurity
    @Trans
    public void doSettingRole() throws ServletException, IOException {
        String[] ids = userDao.getUserRoles(this.I("id"));
        this.assign("uid", this.I("id"));
        this.assign("organId", this.I("organId"));
        this.assign("roleIds", JsonUtils.convertToString(ids));
        this.display("/security/user/settingRole.html");
    }

    @Trans
    @RSSecurity(retType = RSSecRetType.retJson)
    public void doEditUserRole() throws IOException {
        String uid = I("uid");
        String roleId = I("roleId");
        String[] roleIds = roleId.split(",");
        this.print(userDao.editUserRole(uid, roleIds));
    }

    @RSSecurity
    public void doListUser() throws ServletException, IOException {
        this.display("/security/user/listUserOrgan.html");
    }

    @RSSecurity(retType = RSSecRetType.retJson)
    public void doListUserByOrgan() throws IOException {
        String myOrganId = rSUserInfo.getOrganId();
        String queryOrganId = this.I("organId");
        if (StringUtils.isEmpty(this.I("organId"))) {
            queryOrganId = myOrganId;
        }
        Record record = new Record();
        Map paramSet = (Map) this.getParamSet(false);
        record.fromBeanMap((Map) paramSet.get("__data__"));
        DataSet ret = userDao.queryUserOrgan(record, (int) paramSet.get("__offset__"),
                (int) paramSet.get("__limit__"));
        this.print(JsonUtils.convertToString(ret));
    }

    @RSSecurity
    public void doSettingOrgan() throws ServletException, IOException {
        this.assign("userId", this.I("id"));
        this.display("/security/user/settingOrgan.html");
    }

    @Trans
    @RSSecurity(retType = RSSecRetType.retJson)
    public void doEditUserOrgan() throws IOException {
        String organId = this.I("organId");
        String userId = this.I("userId");
        int ret = userDao.editUserOrgan(userId, organId);
        this.print(ret);
    }
}
